<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 搜索框区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" clearable @clear="getQueryInfo" v-model="queryInfo.query">
            <el-button slot="append" icon="el-icon-search" @click="getQueryInfo"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userStateChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark" content="修改信息" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editDialog(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <!-- 分配角色按钮 -->
            <el-tooltip effect="dark" content="角色分配" placement="top" :enterable="false">
              <el-button
                type="success"
                icon="el-icon-coordinate"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除用户" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="delUserInfoById(scope.row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框 -->
    <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" @close="resetAddForm">
      <!-- 主体内容区域 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" type="password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改" :visible.sync="editDialogState" width="50%" @close="editDialogClose">
      <el-form :model="editForm" :rules="addFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱地址" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogState = false">取 消</el-button>
        <el-button type="primary" @click="submitUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%" @close="closeAllotRoleDialog">
      <p>当前的用户:{{Role.username}}</p>
      <p>当前的角色:{{Role.role_name}}</p>
      <p>
        将要分配的新角色:
        <el-select v-model="selectRoleId" placeholder="请选择">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          ></el-option>
        </el-select>
      </p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //   自定义验证规则
    var checkMobile = (rule, value, callback) => {
      var regMobile = /^1(3|4|5|7|8)\d{9}$/
      if (regMobile.test(value)) return callback()
      return callback(new Error('请输入正确的手机号'))
    }
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      userList: [],
      total: 0,
      //   监听添加用户对话框的显示与隐藏
      addDialogVisible: false,
      //   监听修改用户对话框的显示与隐藏
      editDialogState: false,
      //   添加用户表单对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户表单验证规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名长度在3~10个字符之间',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '密码长度在6~16个字符之间',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur']
          }
        ],
        mobile: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      //   修改用户表单对象
      editForm: {},
      setRoleDialogVisible: false,
      // 将要分配角色的信息
      Role: {},
      // 所有角色选项
      roleList: [],
      // 将要分配角色的ID
      selectRoleId: ''
    }
  },
  created() {
    this.getQueryInfo()
  },
  methods: {
    async getQueryInfo() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.userList = res.data.users
      this.total = res.data.total
    },
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize
      this.getQueryInfo()
    },
    handleCurrentChange(newpagenum) {
      this.queryInfo.pagenum = newpagenum
      this.getQueryInfo()
    },
    // 监听用户状态改变
    async userStateChange(userinfo) {
      const { data: res } = await this.$http.put(
        `users/${userinfo.id}/state/${userinfo.mg_state}`
      )
      if (res.meta.status !== 200) {
        userinfo.mg_state = !userinfo.mg_state
        return this.$message({
          type: 'error',
          message: res.meta.msg,
          duration: 1000
        })
      }
      return this.$message({
        type: 'success',
        message: res.meta.msg,
        duration: 1000
      })
    },
    resetAddForm() {
      // 当添加用户对话框关闭的时候，重置表单对象
      this.$refs.addFormRef.resetFields()
    },
    addUser() {
      // 预验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 如果校验通过，那么则发起添加用户的网络请求
        const { data: res } = await this.$http.post('users', this.addForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.getQueryInfo()
        this.addDialogVisible = false
        return this.$message.success(res.meta.msg)
      })
    },
    // 点击修改按钮触发的函数
    async editDialog(id) {
      this.editDialogState = true
      const { data: res } = await this.$http.get(`users/${id}`)
      this.editForm = res.data
    },
    // 提交修改用户信息
    submitUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.getQueryInfo()
        this.editDialogState = false
        return this.$message.success(res.meta.msg)
      })
    },
    // 重置修改表单错误提示消息
    editDialogClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击删除按钮询问管理员是否删除
    async delUserInfoById(userId) {
      await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // 如果确认删除用户 那么发送http请求
          const { data: res } = await this.$http.delete(`users/${userId}`)
          if (res.meta.status !== 200) {
            this.$message({
              type: 'success',
              message: '删除成功!',
              duration: 1000
            })
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!',
              duration: 1000
            })
          }
          this.getQueryInfo()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
            duration: 1000
          })
        })
    },
    // 点击分配角色按钮 显示分配角色对话框
    async setRole(role) {
      this.setRoleDialogVisible = true
      this.Role = role
      // 在分配角色之前先获取所有可以选择的角色
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('获取角色列表失败')
      }
      this.roleList = res.data
    },
    // 提交要重新分配角色的用户ID
    async allotRole() {
      if (!this.selectRoleId) {
        return this.$message.error('请选择要分配的角色')
      }
      this.setRoleDialogVisible = false
      const { data: res } = await this.$http.put(`users/${this.Role.id}/role`, {
        rid: this.selectRoleId
      })
      if (res.meta.status !== 200) {
        return this.$message.error('分配角色失败')
      } else {
        this.getQueryInfo()
        return this.$message.success('分配角色成功')
      }
    },
    // 重置角色分配对话框内容
    closeAllotRoleDialog() {
      this.selectRoleId = ''
    }
  }
}
</script>

<style lang="less" scoped>
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
</style>
